package org.game.module.event.handler;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.cfg.EventConditionCfg;
import org.cfg.MultiConditionEventCfg;
import org.cfg.cache.EventConditionCfgCache;
import org.cfg.cache.MultiConditionEventCfgCache;
import org.constant.EventConditionKey;
import org.constant.smallkey.WorkLogSmallKey;
import org.game.db.bean.Building;
import org.game.db.bean.Player;
import org.game.db.cache.BuildingCache;
import org.game.manager.ItemPackageHelper;
import org.game.msgBuilder.BuildingMsgBuilder;
import org.game.plugin.event.GameEvent;
import org.game.plugin.event.GameEventHandler;
import org.game.plugin.event.GameEventListener;
import org.game.plugin.event.GameEventStack;
import org.utils.CommonUtil;

import com.google.common.collect.Maps;
import com.google.common.collect.RangeMap;
import com.google.common.collect.Sets;
import com.google.common.collect.TreeRangeMap;
import com.sojoys.artifact.constant.ArtifactErrorCode;
import com.sojoys.artifact.tools.ToolDate;
import com.sojoys.artifact.tools.ToolError;
import com.sojoys.artifact.tools.ToolMap;
import com.sojoys.artifact.tools.ToolRandom;

/**
 * 带权重的事件处理器
 */
public class MultiConditionEventHandler implements GameEventHandler {

	/**
	 * 流程：
	 * 	1.根据条件类型筛选事件
	 * 	2.筛选出达成条件的事件
	 * 	3.通过权重获取最终事件
	 * 	4.执行事件结果
	 */
	@Override
	public void onEvent(GameEventListener listener, GameEvent event) {
		int conditionType = event.getConditionType();
		if(conditionType == 0){
			return;
		}
		//1.根据条件类型筛选事件
		List<MultiConditionEventCfg> cfgList = MultiConditionEventCfgCache.me().getByEventConditionId(conditionType);

		// 达成的配置
		Set<MultiConditionEventCfg> reachs = Sets.newHashSet();

		//2.筛选出达成条件的事件
		// 海选，选出类型和sourceId符合条件的
		cfgList.forEach(cfg -> {
			// 验证参数
			if (checkEventSource(cfg, event, listener)) {
				reachs.add(cfg);
			}
		});

		//3.通过权重获取最终事件
		int totalWeight = 0;
		int nowWeight = 0;
		for (MultiConditionEventCfg cfg : reachs) {
			totalWeight += cfg.getWeight();
		}

		int randomWeight = ToolRandom.randInt(0, totalWeight);

		for (MultiConditionEventCfg cfg : reachs) {
			nowWeight += cfg.getWeight();
			if (nowWeight >= randomWeight) {
				//4.执行事件结果
				eventResult(event, cfg.getResult() , cfg);
				break;
			}
		}
	}

	/**
	 * 校验事件源
	 */
	private boolean checkEventSource(MultiConditionEventCfg cfg, GameEvent event,GameEventListener listener) {
		event.push(new GameEventStack(0,event.getConditionType(), cfg.getCondition(), 0, 0, false));
		listener.onEvent(event);
		GameEventStack eventStack = event.peek();
		return eventStack.isTrigger();
	}
}
